<template>
  <view class="account-item" @click="handleClick">
    <!-- 左侧图标和信息 -->
    <view class="item-left">
      <view class="avatar" :style="{ backgroundColor: avatarColor }">
        <text class="avatar-text">{{ getAvatarText(account.title) }}</text>
      </view>

      <view class="info">
        <view class="title-row">
          <text class="title">{{ account.title }}</text>
          <view v-if="account.is_favorite" class="favorite-icon">
            <text>⭐</text>
          </view>
        </view>

        <view class="subtitle-row">
          <text v-if="account.username" class="username">{{ account.username }}</text>
          <text v-if="account.website" class="website">{{ formatWebsite(account.website) }}</text>
        </view>

        <view v-if="showExtraInfo" class="extra-info">
          <text v-if="account.category" class="category">{{ account.category.name }}</text>
          <text v-if="account.last_used_at" class="last-used">
            最近使用: {{ formatTime(account.last_used_at) }}
          </text>
        </view>
      </view>
    </view>

    <!-- 右侧操作按钮 -->
    <view class="item-right">
      <!-- 过期提醒 -->
      <view v-if="isExpiring" class="expire-badge">
        <text>即将过期</text>
      </view>

      <!-- 操作按钮 -->
      <view class="actions">
        <view class="action-btn copy-btn" @click.stop="handleCopyPassword">
          <text class="action-icon">📋</text>
        </view>

        <view v-if="showMoreActions" class="action-btn more-btn" @click.stop="handleMoreActions">
          <text class="action-icon">⋯</text>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-mask">
      <text class="loading-text">处理中...</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { Account } from '@/api/account'
import { formatRelativeTime } from '@/utils/common'

interface AccountItemProps {
  account: Account
  showExtraInfo?: boolean
  showMoreActions?: boolean
}

interface AccountItemEmits {
  (event: 'click', account: Account): void
  (event: 'copy', account: Account): void
  (event: 'more', account: Account): void
}

const props = withDefaults(defineProps<AccountItemProps>(), {
  showExtraInfo: false,
  showMoreActions: true
})

const emit = defineEmits<AccountItemEmits>()

// 响应式数据
const isLoading = ref(false)

// 计算属性
const avatarColor = computed(() => {
  // 根据账号标题生成颜色
  const colors = [
    '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
    '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9'
  ]

  let hash = 0
  for (let i = 0; i < props.account.title.length; i++) {
    hash = props.account.title.charCodeAt(i) + ((hash << 5) - hash)
  }

  return colors[Math.abs(hash) % colors.length]
})

const isExpiring = computed(() => {
  if (!props.account.expires_at) return false

  const now = new Date()
  const expiresAt = new Date(props.account.expires_at)
  const daysUntilExpiry = Math.ceil((expiresAt.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))

  return daysUntilExpiry <= 7 && daysUntilExpiry > 0
})

// 获取头像文字
const getAvatarText = (title: string): string => {
  if (!title) return '?'

  // 中文取第一个字
  if (/[\u4e00-\u9fa5]/.test(title)) {
    return title.charAt(0)
  }

  // 英文取前两个字母
  const words = title.split(' ').filter(word => word.length > 0)
  if (words.length >= 2) {
    return (words[0].charAt(0) + words[1].charAt(0)).toUpperCase()
  }

  return title.charAt(0).toUpperCase()
}

// 格式化网站地址
const formatWebsite = (website: string): string => {
  try {
    const url = new URL(website.startsWith('http') ? website : `https://${website}`)
    return url.hostname
  } catch {
    return website
  }
}

// 格式化时间
const formatTime = (time: string): string => {
  return formatRelativeTime(new Date(time))
}

// 处理点击
const handleClick = () => {
  emit('click', props.account)
}

// 处理复制密码
const handleCopyPassword = async () => {
  try {
    isLoading.value = true
    emit('copy', props.account)
  } catch (error) {
    console.error('复制密码失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 处理更多操作
const handleMoreActions = () => {
  emit('more', props.account)
}
</script>

<style lang="scss" scoped>
.account-item {
  position: relative;
  padding: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.2s;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }

  &:last-child {
    margin-bottom: 0;
  }

  .item-left {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;

    .avatar {
      width: 44px;
      height: 44px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

      .avatar-text {
        color: white;
        font-size: 16px;
        font-weight: 600;
      }
    }

    .info {
      flex: 1;
      min-width: 0;

      .title-row {
        display: flex;
        align-items: center;
        gap: 6px;
        margin-bottom: 4px;

        .title {
          font-size: 16px;
          font-weight: 600;
          color: #1a1a1a;
          flex: 1;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        .favorite-icon {
          text {
            font-size: 14px;
          }
        }
      }

      .subtitle-row {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 2px;

        .username {
          font-size: 14px;
          color: #666;
        }

        .website {
          font-size: 12px;
          color: #999;
          background: #f5f5f5;
          padding: 2px 6px;
          border-radius: 4px;
        }
      }

      .extra-info {
        display: flex;
        align-items: center;
        gap: 8px;

        .category {
          font-size: 12px;
          color: #1890ff;
          background: rgba(24, 144, 255, 0.1);
          padding: 2px 6px;
          border-radius: 4px;
        }

        .last-used {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }

  .item-right {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 8px;

    .expire-badge {
      padding: 2px 6px;
      background: #ff4d4f;
      border-radius: 4px;

      text {
        font-size: 10px;
        color: white;
      }
    }

    .actions {
      display: flex;
      gap: 8px;

      .action-btn {
        width: 36px;
        height: 36px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;

        .action-icon {
          font-size: 16px;
        }

        &:active {
          transform: scale(0.9);
        }
      }

      .copy-btn {
        background: rgba(24, 144, 255, 0.1);

        .action-icon {
          color: #1890ff;
        }

        &:active {
          background: rgba(24, 144, 255, 0.2);
        }
      }

      .more-btn {
        background: rgba(0, 0, 0, 0.05);

        .action-icon {
          color: #666;
        }

        &:active {
          background: rgba(0, 0, 0, 0.1);
        }
      }
    }
  }

  .loading-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;

    .loading-text {
      font-size: 12px;
      color: #666;
    }
  }
}
</style>